package ru.zombator.taskman.server.query.rmi;

import java.rmi.AlreadyBoundException;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RemoteServer;
import java.rmi.server.ServerNotActiveException;
import java.rmi.server.UnicastRemoteObject;

import ru.zombator.taskman.core.query.IPacket;
import ru.zombator.taskman.core.query.IResponderSvc;
import ru.zombator.taskman.server.query.BaseServer;

/**
 * RMI-сервер.
 * 
 * @see IRmiServer
 * @see IResponderSvc
 * @author nvamelichev
 * 
 */
public class RmiServer extends BaseServer implements IRmiServer, IResponderSvc {
	private static final long serialVersionUID = 1L;
	private static final String SERVER_NAME = "dist-taskman";

	private IRmiServer stub;

	@Override
	public IPacket getResponse(IPacket request) throws RemoteException {
		try {
			return getResponse(request, RemoteServer.getClientHost());
		} catch (ServerNotActiveException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Создает RMI-сервер, регистрирующий сам себя под именем
	 * {@link #SERVER_NAME}.
	 * 
	 * @throws RemoteException
	 *             не удалось зарегистрироваться
	 * @throws AlreadyBoundException
	 *             уже зарегистрирован
	 */
	public RmiServer() throws RemoteException, AlreadyBoundException {
		stub = (IRmiServer) UnicastRemoteObject.exportObject(this, 0);
		Registry registry = LocateRegistry.getRegistry();
		registry.bind(SERVER_NAME, stub);
	}

	@Override
	public void dispose() {
		Registry registry;
		try {
			registry = LocateRegistry.getRegistry();
			registry.unbind(SERVER_NAME);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		try {
			UnicastRemoteObject.unexportObject(this, true);
		} catch (NoSuchObjectException e) {
			e.printStackTrace();
		}
	}
}
